﻿@Cofe ?= {}
Link = Cofe.Link
Entry = Cofe.Entry
EntryList = Cofe.EntryList

# MODEL - Represents a COFEWS EntryList.
# events - fetched, error
# variables - status = notready, working, ready, error
class EntryList extends Spine.Model
  # url - url the entrylist loaded from, e.g. a /search or /entry/{guid}/list
  # entryIds - Id of the entries in the entry list, entry are saved separately.
  # status - current status of the entry list (notready -> working -> ready)
  @configure 'EntryList', 'url', 'entryIds', 'status', 'links', 'currentPage', 'totalPages', 'itemsPerPage', 'totalEntries'
  
  @constructor : ->
    @entries = []

  init : =>        
    @status = "notready" 
  
  # Construct an EntryList from a url, which returns a COFEWS EntryList obj in json.
  EntryList.fromUrl = (url) ->   
    elist = EntryList.findByAttribute('url', url) #Look from cache
    if elist isnt null 
    then elist.regenerate()
    else new EntryList({ url : url, links : {} })
  
  # Construct from Json
  EntryList.fromJson = (data, url) ->
     elist = new EntryList({ url : url, links : {} })
     elist.refresh(data)
     elist

  EntryList.fromEntries = (entries) ->
     entryIds = (for entry in entries
       entry.id)
     elist = new EntryList({ entries : entries, entryIds : entryIds })
     elist.status = "ready"
     elist
  
  EntryList.remove = (url) ->
     elist = EntryList.findByAttribute('url', url)
     if (elist isnt null)
       elist.destroy()
       #EntryList.destroy(url)

  toJson : (exposedProps) =>
    elist = new Object()
    elist.entries = (entry.toJson(exposedProps) for entry in @entries) 
    return elist

  # If cached, regenerate @entries (a list of Entry) from @entryIds (a list of Entry Ids)
  regenerate : =>
    @entries = (for entryId in @entryIds
       Entry.fromId(entryId))
    @status = "ready"
    @

  # If not cached, after a success fetch operation, create entries from json.
  # then save to cache, and raise fetched event.
  refresh : (data) ->
    log.debug("EntryList: refreshing " + @url)
    @type = data.type
    
    @currentPage = data.currentPage
    @totalPages = data.totalPages
    @itemsPerPage = data.itemsPerPage
    @totalEntries = data.totalEntries

    @entries = (for entryData in data.entries 
       Entry.fromJson(entryData))
    
    #Sort entry list.  
    @entries.sort((a,b) -> a.compare(b)) 

    if data.links != undefined
      #Add links
      for link in data.links
        linkObj = Link.fromJson(link)
        @links[linkObj.rel] = linkObj


    @entryIds = (for entryData in @entries 
       entryData.id)
    @status = "ready"

    if @url isnt null
      @save()
    
    @trigger("fetched", @)  
  
  # Get the @url, and calls @refresh if success, trigger error if fails.
  fetch : =>  
    @status = "working"
    log.debug("EntryList: fetching " + @url)
    $.getJSON(@url)
      .success((xhr, s, e) =>
        log.debug("EntryList: fetched " + @url)
        @refresh(xhr)
      )
      .error((xhr, s, e) => 
        @status = "error"        
        log.error("EntryList: fetch failed " + e + " - " + @url)
        @trigger("error", e, s, xhr)
      )
  
 

Cofe.EntryList = EntryList